﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DeVierKoeden.Dynamicweb.CreateSite.Extensions;
using Microsoft.Web.Administration;

namespace DeVierKoeden.Dynamicweb.CreateSite
{
  public partial class IgnoreFolders : Form
  {
    private readonly FileExplorer _fileExplorer = new FileExplorer();
    private Site _siteToBackup;

    public IgnoreFolders()
    {
      InitializeComponent();
    }

    public string[] FoldersToIgnore
    {
      get
      {
        if (SiteToBackup == null)
        {
          // Can be null when deleting a site
          return new string[] { };
        }
        var rootFolder = SiteToBackup.GetFilesPath();
        var selectedNodes = treeView1.GetAllNodes().Where(x => x.Checked);
        return selectedNodes.Select(x => x.Tag.ToString().Replace(rootFolder, "Files").Replace("\\", "\\\\")).ToArray();
      }
    }

    void ClearSelectedFolders()
    {
      treeView1.Nodes.Clear();
    }

    public Site SiteToBackup
    {
      get { return _siteToBackup; }
      set
      {
        _siteToBackup = value;
        ClearSelectedFolders();
        CreateTreeFromSite();
      }
    }

    private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
    {
      if (e.Node.Nodes[0].Text == "")
      {
        _fileExplorer.EnumerateDirectory(e.Node);
      }
    }

    private void CreateTreeFromSite()
    {
      _fileExplorer.CreateTree(treeView1, SiteToBackup.GetFilesPath());
      treeView1.Nodes[0].Expand();
    }

    private void IgnoreFolders_FormClosing(object sender, FormClosingEventArgs e)
    {
      if (e.CloseReason == CloseReason.UserClosing)
      {
        e.Cancel = true;
        Hide();
      }
    }

    private void close_Click(object sender, EventArgs e)
    {
      Hide();
    }

    private void selectCommonlyIgnoredFolders_Click(object sender, EventArgs e)
    {
      var pathsToSelect = new[] { "Cache.net", "Papirkurv", "Diagnostics", "System\\Log", "System\\Packages" };
      var rootFolder = SiteToBackup.GetFilesPath();

      var systemNode = treeView1.GetAllNodes().FirstOrDefault(x => x.Tag != null && x.Tag.ToString().Equals(rootFolder + "\\System", StringComparison.CurrentCultureIgnoreCase));
      systemNode?.Expand(); // Load sub folders like Log and Packages
      var nodesToSelect = new List<TreeNode>();

      foreach (var node in treeView1.GetAllNodes())
      {
        foreach (var path in pathsToSelect)
        {
          if (node.Tag != null && node.Tag.ToString().Equals(string.Format("{0}\\{1}", rootFolder, path), StringComparison.CurrentCultureIgnoreCase))
          {
            nodesToSelect.Add(node);
            break;
          }
        }
      }
      nodesToSelect.ForEach(x => x.Checked = true);
    }
  }
}
